<template>
  <div>
    <el-row>
      <el-tag v-for="(item, index) in relateItems" :key="item.label" closable effect="dark" @close="delRelateItem(index)" style="margin: 0 5px 5px 0" size="small">{{ item.label }}</el-tag>
    </el-row>
    <el-row>
      <el-select v-model="currentFirst" placeholder="请选择" size="small" value-key="id" @change="loadSecondData" style="width: 100px">
        <el-option v-for="(item,index) in relateList" :key="item.id" :value="item" :label="item.label">
          <span v-if="required[index]" style="color: red">*</span>
          <span>{{ item.label }}</span>
<!--          <span v-if="required[index]">(必填)</span>-->
          <el-tag v-if="required[index]" type="danger" style="margin-left: 5px">必填项</el-tag>
        </el-option>
      </el-select>
      <el-select
          v-if="currentFirst.code != 'Order'"
          v-model="currentSecond"
          placeholder="请选择"
          size="small"
          value-key="id"
          style="margin-left: 10px;width: 150px"
          :remote="true"
          :remote-method="secondSearch"
          :loading="secondLoading"
          :disabled="!(currentFirst && currentFirst.id)"
          @change="secondChange"
          :filterable="true">
        <el-option v-for="item in secondList" :key="item.id" :value="item" :label="item.name || item.shortName" />
      </el-select>
      <el-button size="small" type="primary" v-else @click="loadSecondData(currentFirst)" style="margin-left: 10px">选择订单</el-button>
      <el-select
          v-model="currentThird"
          placeholder="请选择"
          size="small"
          value-key="id"
          v-show="currentFirst.code === 'Customer'"
          :disabled="!(currentSecond && currentSecond.id)"
          filterable
          :remote="true"
          :remote-method="thirdSearch"
          :loading="thirdLoading"
          @change="canFormatData"
          style="margin-left: 10px;width: 150px"
          clearable>
        <el-option v-for="item in thirdList" :key="item.id" :value="item" :label="item.name"/>
      </el-select>
      <el-input size="small" style="width: 150px;margin-left: 10px" placeholder="市场项目(选填)" v-model="currentFourth" v-if="isShowFourth && isShowOptional" clearable />
      <el-button size="small" type="primary" @click="formatData" v-if="isShowFourth" style="margin-left: 10px">添加关联</el-button>
    </el-row>

    <el-dialog v-model="orderVisible" :append-to-body="true" width="900px" title="订单" @opened="defaultSelected">
      <el-table :data="orderList" stripe border size="small" ref="orderTableRef" :header-cell-style="{textAlign: 'center', background: 'var(--el-color-primary-light-9)', color: 'var(--next-bg-menuBar-light-1)'}" :cell-style="{textAlign: 'center'}" @selection-change="orderChange">
        <el-table-column type="selection" width="60"/>
        <el-table-column label="订单号" prop="orderSn" width="120"/>
        <el-table-column label="客户名称" prop="customerName"/>
        <el-table-column label="订单类型" width="90">
          <template v-slot="{row}">{{ row.classOther == 0 ? '个人' : '企业' }}</template>
        </el-table-column>
        <el-table-column label="订单来源" width="90">
          <template v-slot="{row}">
            <span v-if="row.sourceType == 0">官网商城</span>
            <span v-else-if="row.sourceType == 1">17购</span>
            <span v-else-if="row.sourceType == 2">手动录入</span>
            <span v-else-if="row.sourceType == 3">17合约</span>
            <span v-else>核销订单</span>
          </template>
        </el-table-column>
        <el-table-column label="产品名称" prop="productNames"/>
        <el-table-column label="订单总金额" prop="totalAmount"/>
        <el-table-column label="订单阶段" width="100">
          <template v-slot="{row}">{{ orderStage[row.status] }}</template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button size="small" type="primary" @click="confirmOrder">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {onMounted, reactive, toRefs, ref, watch} from 'vue'
import {getRelateItems, getRelateDataList, getCustomerOrders, getOrderPage} from '/@/api/matter'
import {ElMessage} from 'element-plus'
import purchaseOrderApi from '/@/api/supplier/purchaseOrder'
import {getDeptName} from "../../../api/sys/dept";
import {getUserDept} from "../../../api/oa/dept";

export default {
  name: 'ModuleRelate',
  props: {
    relateItems: {
      type: Array,
      default: []
    },
    selected: {   // 默认选中的
      type: Object,
      default: {
        code: null,   // 一级关联项数据code
        dataId: null // 二级关联项数据id
      }
    },
    limiter:{ //用于钱模块的各种奇怪限制
      type:Object,
      default: {
        module:null, //代表哪一个模块
        number:null  //代表限制编号
      }
    }
  },
  emits:['required','change','update:relateItems'],
  setup(props, context) {
    const orderTableRef = ref()
    const {relateItems, selected, limiter} = toRefs(props)
    //TODO 监听限制器变化
    watch(limiter, (newVal) => {
      if(newVal){
        executeLimiter(newVal)
      }
    },{deep: true})
    const state = reactive({
      required:[], //必填项开关 默认都是false
      currentFirst: {}, // 拿整个对象
      currentSecond: {},
      secondParams: {
        current: 1,
        size: 999,
        name: null
      },
      secondLoading: false,
      thirdLoading: false,
      currentThird: {},
      currentFourth: '',
      thirdParams: {
        current: 1,
        size: 999,
        name: null,
        memberId: null
      },
      onlyExecuteOnce: true,
      relateList: [], // 一级可关联项列表
      secondList: [], // 二级对象列表
      thirdList: [],  // 三级对象列表 部分二级对象数据没有三级对象列表
      fourthList:[],  // 四级对象列表 选填项
      orderVisible: false,  // 订单弹窗
      orderList: [],
      orderParams: {
        pageNum: 1,
        pageSize: 10,
        selectSource: 1
      },
      isShowFourth:false,
      isShowOptional:true,
      orderTotal: 0,
      selectedOrders: [],
      orderStage: {   // 订单阶段
        '0': '待付款',
        '1': '待发货',
        '2': '已发货',
        '3': '已完成',
        '4': '已关闭',
        '5': '无效订单',
        '6': '待审批',
        '7': '已审批',
        '8': '待退款',
        '9': '待退货',
        '10': '已签收',
        '11': '重发补发',
        '12': '退货',
        '13': '退款',
        '14': '退货退款'
      }
    })

    const loadSecondData = (val) => {
      if (val.code == 'Order') {
        getOrderPage(state.orderParams).then(res => {
          let data = res.data.list
          state.orderList = data.records
          state.orderTotal = data.total
          // 判断是否已有选中订单
          state.selectedOrders = []
          if (relateItems.value && state.orderList.length > 0 && relateItems.value.length > 0) {
            state.orderList.forEach(order => {
              let productNames = ''
              if (order.orderItemList.length > 0) {
                order.orderItemList.forEach(product => productNames += product.skuName + '，')
                productNames = productNames.substring(0, productNames.length - 1)
              }
              order.productNames = productNames
              for (let i = 0; i < relateItems.value.length; i++) {
                let item = relateItems.value[i]
                if (item.label.indexOf('订单') > -1 && item.seRelateDataId == order.orderSn) {
                  state.selectedOrders.push(order)
                  break
                }
              }
            })
          }
          state.orderVisible = true
        }).catch(e => console.log(e))
      }else if (val.identifyName) {
        getRelateDataList(val.identifyName, state.secondParams).then(res => {
          state.secondList = [] //初始化
          state.secondList = state.secondList.concat(res.data.records)
          if (selected.value && selected.value.dataId) {
            for (let i = 0; i < state.secondList.length; i++) {
              state.secondList[i]['label'] = state.secondList[i]['shortName']
              let data = state.secondList[i]
              if (data.id == selected.value.dataId) {
                state.currentSecond = data
                formatData()
                break
              }
            }
          }
        })
      }
    }
    const secondSearch = (search) => {
      state.secondList = state.thirdList = []
      state.currentThird = {}
      state.thirdParams = {
        current: 1,
        size: 999,
        name: null,
        memberId: null
      }
      state.secondParams.name = search
      loadSecondData(state.currentFirst)
    }
    const secondChange = (val) => {
      // 目前只有客模块有第三级 -> 加载对应客户订单数据
      if (state.currentFirst.moduleCode === 'Customer') {
        state.thirdParams.memberId = val.id
        getCustomerOrders(state.thirdParams).then(res => {
          if (res.data.records.length > 0) {
            state.thirdList = res.data.records
          } else {
            ElMessage.warning('客户订单为空')
            state.currentThird = {}
            state.thirdList = []
            canFormatData()
          }
        })
      }else if(state.currentFirst.code === 'Project'){ //项目加入第三级数据->部门(自动选择无法更改)
        getDeptName(val.deptId).then(res=>{
          if(res.data){
            state.currentThird.id = val.id
            state.currentThird.name = res.data
            canFormatData()
          }
        })
      }else if(state.currentFirst.code === 'Market'){ //市场加入第三级数据->部门(负责人所在部门,自动选择无法更改)
        getUserDept({userId:val.dutyUserId,enterpriseId:val.enterpriseId}).then(res=>{
          if(res.data){
            state.currentThird.id = res.data.id
            state.currentThird.name = res.data.name
            canFormatData()
            state.currentSecond = {}
          }else{
            ElMessage.warning('负责人在当前公司没有绑定部门')
            state.currentThird = {}
            state.thirdList = []
            canFormatData()
          }
        })
      } else if(state.currentFirst.code === 'Purchase'){ //采购单加入第三级数据->订单ID
        //FIXME 不过事项模块暂时没有采购单
        state.thirdParams.memberId = val.id
        purchaseOrderApi.getOrderPage({current:1,size:500,shortName:val.shortName}).then(res => {
          if (res.data.records.length > 0) {
            state.thirdList = res.data.records
          } else {
            ElMessage.warning('采购订单为空')
            state.currentThird = {}
            state.thirdList = []
            canFormatData()
          }
        })
      } else {  // 直接提交已选数据到父组件
        canFormatData()
      }
    }
    const thirdSearch = (search) => {
      state.thirdList = []
      state.thirdParams.name = search
      getCustomerOrders(state.thirdParams).then(res => state.thirdList = res.data.records)
    }
    const delRelateItem = (index) => {
      if(limiter.value.module === 'saleReceivable'){//当前限制器为销售应收时 不可删除
        ElMessage.warning("当前状态不可删除")
        return;
      }
      relateItems.value.splice(index, 1)
      context.emit('update:relateItems', relateItems)
      context.emit('change', relateItems)
    }
    const formatData = () => {
      let itemArr = relateItems.value
      if (itemArr.length > 0) {
        let flag = false
        for (let i = 0; i < itemArr.length; i++) {
          flag = itemArr[i].agendaMatterRelatableId === state.currentFirst.id && itemArr[i].seRelateDataId === state.currentSecond.id
          if (state.currentThird.id) {
            flag = itemArr[i].thRelateDataId === state.currentThird.id
          }
          if (flag) {
            break
          }
        }
        if (flag) {
          return
        }
      }

      if(state.currentFirst.id == null || state.currentSecond.id == null && state.isShowFourth){
        ElMessage.warning("请填写数据")
        return;//直接结束 不添加
      }
      let item = {
        agendaMatterRelatableId: state.currentFirst.id,
        code: state.currentFirst.code,
        seRelateDataId: state.currentSecond.id,
        thRelateDataId: state.currentThird.id || null,
        label: state.currentFirst.label + '/' + (state.currentSecond.name || state.currentSecond.shortName) + (state.currentThird.id ? ('/' + state.currentThird.name) : '') + (state.currentFourth == null || state.currentFourth === '' ? '' : '/'+state.currentFourth),
        remark:state.currentFourth
      }
      /**
       * 目前六种事项可以分成两种类型 一种需要relateItems 另一种不需要
       */
      if (state.onlyExecuteOnce) {
        if (relateItems.value.length > 0) {
          itemArr[0]['agendaMatterRelatableId'] = item.agendaMatterRelatableId
          itemArr[0]['seRelateDataId'] = item.seRelateDataId
          itemArr[0]['thRelateDataId'] = item.thRelateDataId
          itemArr[0]['label'] = item.label
          itemArr[0]['remark'] = item.currentFourth
        } else {
          itemArr.push(item)
        }
        context.emit('update:relateItems', itemArr)
        context.emit('change', itemArr)
        state.onlyExecuteOnce = false
      } else {
        itemArr.push(item)
      }
      state.currentThird = {}
    }
    const canFormatData = () => {
      if(!state.isShowFourth){
        formatData()
        state.currentSecond = {}
      }
    }

    const initData = () => {
      state.secondList = state.thirdList = []
      state.currentSecond = state.currentThird = {}
      state.thirdParams = {
        current: 1,
        size: 999,
        name: null,
        memberId: null
      }
      state.secondParams = {
        current: 1,
        size: 999,
        name: null
      }
      state.currentFourth = ''
    }
    // 订单表格选中
    const orderChange = (val) => state.selectedOrders = val
    // 确定选择订单
    const confirmOrder = () => {
      if (state.selectedOrders.length > 0) {
        state.selectedOrders.forEach(order => {
          state.currentSecond = {
            id: order.id,
            name: order.orderSn
          }
          formatData()
        })
      }
      state.orderVisible = false
      state.selectedOrders = []
    }
    // 选中的订单
    const defaultSelected = () => {
      if (state.selectedOrders.length > 0) {
        orderTableRef.value.toggleRowSelection(state.selectedOrders, true)
      }
    }
    //执行限制器
    const executeLimiter = (newVal) => {
      if(newVal.module != null && newVal.number != null){
        //当前仅钱有限制
        switch (newVal.module){
          case "income": incomeLimiter(newVal.number);break;
          case "expenditure": expenditureLimiter(newVal.number);break;
          case "paymentOrder": paymentOrderLimiter(newVal.number);break;
          case "saleReceivable": saleReceivableLimiter(newVal.number);break;
          case "badDebts": badDebtsLimiter(newVal.number);break;
          case "exemptPay": exemptPayLimiter(newVal.number);break;
          case "createInvoice": createInvoiceLimiter(newVal.number);break;
          // default:ElMessage.error("参数错误");
        }
      }
    }
    //钱模块限制
    const incomeLimiter = (number) => {
      initData()
      if(number === '0'){
        //关联没有供应商可选；如果有待付款的线下转账的电商单才有客可以选，且线下转账的电商单必选
        getRelateItems().then(res => {
          state.required = new Array(res.data.length).fill(false) //初始化为false
          for (let i = 0; i < res.data.length; i++) {
            if(res.data[i].code === 'Supplier'){ //剔除供应商
              res.data.splice(i, 1)
              break
            }
          }
          // if(如果需要客必填项){
          //   for (let i = 0; i < res.data.length; i++) {
          //     if(res.data[i].code === 'Customer'){ //找到客
          //       state.required[i] = true
          //       break
          //     }
          //   }
          // }
          state.relateList = res.data
        })
      }else if(number === '1'){
        addRequired(['Customer'])
      }else if(number === '2'){
        addRequired(['Supplier','Purchase'])
      }else if(number === '3'){

      }
    }
    const expenditureLimiter = (number) => {
      initData()
      if(number === '0'){

      }else if(number === '1'){
        addRequired(['Supplier','Purchase'])
      }else if(number === '2'){
        addRequired(['Customer'])
      }
    }
    const paymentOrderLimiter = (number) => {
      //在PaymentOrder为状态2时,此处要求和expenditureLimiter 完全一致
      initData()
      if(number === '0'){

      }else if(number === '1'){
        addRequired(['Supplier','Purchase'])
      }else if(number === '2'){
        addRequired(['Customer'])
      }
    }
    const saleReceivableLimiter = (number) => {
      initData()
      //此处number无效 因为只有1个
      addRequired([],['Customer','Order','Office','Product','Money','Supplier','Purchase']) //只保留项目和市场
    }
    const badDebtsLimiter = (number) => {
      initData()
      //此处number无效 因为只有1个
      addRequired(['Customer'])
    }
    const exemptPayLimiter = (number) => {
      initData()
      //此处number无效 因为只有1个
      addRequired(['Customer'],[],true)
    }
    const createInvoiceLimiter = (number) => {
      initData()
      //此处number无效 因为只有1个
      state.isShowOptional = false //此处不需要选填项
      addRequired(['Customer'],['Order','Office','Product','Money','Supplier','Purchase','Market','Project'],true) //只保留客户
    }

    //TODO 添加必填项 必填项将在提交时进行校验
    //val->添加模块必选项
    //remove->删除模块项
    //isShowFourth->是否显示第四项选填数据 (XX项目市场)  默认false,打开后会改为手动添加关联
    const addRequired = (val,remove,isShowFourth) => {
      getRelateItems().then(res => {
        if(remove != null && remove.length > 0){
          let len = res.data.length
          for (let i = 0; i < len; i++) {
            const index = remove.indexOf(res.data[i].code)
            if(index !== -1){ //剔除
              res.data.splice(i, 1)
              i--
              len--
            }
          }
        }
        state.relateList = res.data
        state.required = new Array(res.data.length).fill(false) //初始化为false
        if(val != null && val.length > 0){
          for (let i = 0; i < res.data.length; i++) {
            const index = val.indexOf(res.data[i].code);
            if(index !== -1){
              state.required[i] = true //添加必填项
            }
          }
        }
        if(isShowFourth != null && typeof(isShowFourth) === "boolean"){ //默认false
          state.isShowFourth = isShowFourth
        }else{
          state.isShowFourth = false
        }
      })
      context.emit("required",val)//回传必填项
    }


    onMounted(() => {
      initData()
      getRelateItems().then(res => {
        state.relateList = res.data
        if (selected.value && selected.value.code) {
          for (let i = 0; i < state.relateList.length; i++) {
            let item = state.relateList[i]
            if (item.code == selected.value.code) {
              state.currentFirst = item
              loadSecondData(item)
              break
            }
          }
        }
      }).catch(e => console.log(e))
      //其他模块也需要限制此处需添加模块判断
      executeLimiter(limiter.value) //会重复加载数据 能优化
    })

    return {
      orderTableRef,
      ...toRefs(state),
      loadSecondData,
      secondSearch,
      secondChange,
      thirdSearch,
      delRelateItem,
      formatData,
      confirmOrder,
      defaultSelected,
      orderChange,
      incomeLimiter,
      addRequired,
      expenditureLimiter,
      paymentOrderLimiter,
      saleReceivableLimiter,
      executeLimiter,
      badDebtsLimiter,
      createInvoiceLimiter,
      canFormatData,

    }
  }
}
</script>

<style lang="scss" scoped>

</style>
